package com.sys.controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * 鏂囦欢涓婁紶
 *
 * @author Mr.du
 * @date 2021/11/29
 */
@SuppressWarnings("all")
@RestController
public class TaskFileController {
    /**
     * 鏂囦欢涓婁紶
     *
     * @param file    鏂囦欢
     * @param request 璇锋眰
     * @return int
     * @throws IOException ioexception
     * @RequestParam("file") 灏唍ame=file鎺т欢寰楀埌鐨勬枃浠跺皝瑁呮垚CommonsMultipartFile 瀵硅薄
     */
    @RequestMapping("/upload")
    @ResponseBody
    public int fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //鑾峰彇鏂囦欢鍚� : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //濡傛灉鏂囦欢鍚嶄负绌猴紝鐩存帴鍥炲埌棣栭〉锛�
        if ("".equals(uploadFileName)) {
            return 0;
        }
        System.out.println("涓婁紶鏂囦欢鍚� : " + uploadFileName);

        //涓婁紶璺緞淇濆瓨璁剧疆
        String path = request.getSession().getServletContext().getRealPath("/upload");
        //濡傛灉璺緞涓嶅瓨鍦紝鍒涘缓涓�涓�
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("涓婁紶鏂囦欢淇濆瓨鍦板潃锛�" + realPath);
        //鏂囦欢杈撳叆娴�
        InputStream is = file.getInputStream();
        //鏂囦欢杈撳嚭娴�
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
        //璇诲彇鍐欏嚭
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();
        return 1;
    }
}